/*
 *  cda/src/cal_chars.c
 *  (C)
 */

#include <stdio.h>
#include <error.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>

#include "../include/cda.h"

/*
 * cal_ch_fre: calculate the file's characters' amounts.
 * @file_name: get the compression file name.
 * @get_ch_fre: get the character relevant infos.
 */

int 
cal_ch_fre(char *file_name, struct ch_fre *get_ch_fre)
{
	int fd;
	int i;
	char ch;
	int count;
	size_t check;

#if	defined(DEBUG) && (DEBUG == 1)
	for (count = 0; count < CHAR_NUM; count++) 
		printf("%d %d\n", get_ch_fre[count].ch,
					get_ch_fre[count].fre);
	printf("%s\n", file_name);
#endif

	if (-1 == (fd = open(file_name, O_RDONLY))) {
		printf("Open Error!\n");
		return -1;
	}
	do {
		check = read(fd, &ch, (size_t)1);
		if (1 == check) {
			for (i = 0; i < CHAR_NUM; i++) {
				if (ch == get_ch_fre[i].ch) {
					get_ch_fre[i].fre += 1;
				}
			}
		} else if (0 == check) {

#if defined(DEBUG) && (1 == DEBUG)
			printf("Cal character over!\n");
	for (count = 0; count < CHAR_NUM; count++) 
		printf("%d   %d\n", get_ch_fre[count].ch,
					get_ch_fre[count].fre);
	printf("%s\n", file_name);
#endif

			return 0;
		} else {
			printf("Read file error!\n");
			return -1;
		}
	} while (1);
}
